// ==UserScript==
// @name         长沙信用卡抢电影票
// @namespace    http://tampermonkey.net/
// @version      0.3.4
// @description  try to take over the world!
// @author       zhaoyuqi
// @match        http://csbank.egovlife.com/home.html*
// @require      http://libs.baidu.com/jquery/2.0.0/jquery.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

     let date = new Date();
     let week = date.getDay();
     let hour = date.getHours();
     let minute = date.getMinutes();
     let sec = date.getSeconds();

     let targetDate = new Date();
     targetDate.setHours(10)
     targetDate.setMinutes(0)
     targetDate.setSeconds(0)
     targetDate.setMilliseconds(0);

     while(true){
       let targetWeek = targetDate.getDay()
       if(targetWeek!=5){
         targetDate.setDate(targetDate.getDate()+1)
       }else{
         break;
       }
     }

     let count = 0;
     let maxCount =10;
     let quickBuy = function(){
       if(count++>maxCount){
         document.querySelector('.Order_info h3').innerText="*** 抢购次数已达上限 ***";
         return;
       }
       document.getElementsByClassName('ft_r')[0].getElementsByTagName('a')[0].click()
       setTimeout(function(){
           let msg = document.getElementById('msg');
           let buyTip = document.getElementsByClassName('buytip')[0].getAttribute('style');
           if(msg){
               document.getElementsByClassName('yesIKnow')[0].click();
               setTimeout(quickBuy,100);
           }else if(buyTip!='display: none;'){
               document.querySelector('.Order_info h3').innerText="正在自动识别验证码";
           }else{
               document.querySelector('.Order_info h3').innerText="抢购成功！";
           }
       },50);
     }

    window.keyboardInput =function (dom, st) {
        var evt = new InputEvent('input', {
            inputType: 'insertText',
            data: st,
            dataTransfer: null,
            isComposing: false
        });
        dom.value = st;
        dom.dispatchEvent(evt);
    };

    window.postUrl = function(file_base64,dom,callback){
        let data={
            'user':'getpro',
             'pass':'2320693z',
             'codetype':1902,
             'softid':'916697',
             'file_base64':file_base64
         }
        $.post('https://upload.chaojiying.net/Upload/Processing.php',data,(res)=>{
            console.log(res)
            if (res.err_no === 0) {
              keyboardInput(dom,res.pic_str);
              callback();
            } else {
              console.log("请求失败",res)
            }
        })

    }

    window.getBase64ByUrl = function(src, callback, outputFormat) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', src, true);

        xhr.responseType = 'arraybuffer';

        xhr.onload = function(e) {
            if (xhr.status == 200) {
                var uInt8Array = new Uint8Array(xhr.response);
                var i = uInt8Array.length;
                var binaryString = new Array(i);
                while (i--) {
                    binaryString[i] = String.fromCharCode(uInt8Array[i]);
                }
                var data = binaryString.join('');
                var base64 = window.btoa(data);
                var dataUrl = base64;
                callback.call(this, dataUrl);
            }
        };

        xhr.send();
    }

    window.getBase64Image=function(img) {
            var canvas = document.createElement("canvas");
            img.setAttribute('crossOrigin', 'anonymous');
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var dataURL = canvas.toDataURL("image/png");
        console.log(dataURL)
            // return dataURL;
            return dataURL.replace("data:image/png;base64,", ""); 
    }
    let base64Data = "";
    function checkLogin(){
        
        let imgCode = document.querySelector(".imageCode");
        if(!imgCode){
            return;
        }
        imgCode.onload=function(){
            let prev = base64Data;
            base64Data = getBase64Image(imgCode);
            if(prev){
              let doms = document.querySelectorAll('.aui-flex-box input#verificationImageCode');
                let dom = doms[0];
                if(doms.length>1){
                    dom = doms[doms.length-1];
                }
                window.postUrl(base64Data,dom,(res)=>{
                    console.log(res);
                })
            }
        }
    }

    checkLogin();

    function checkBuyCode(){

        let imgCode = document.querySelector(".imgcode img");
        if(!imgCode){
            return;
        }
        console.log(">> 购买验证码dom 存在");
        //document.querySelector('.buytip').style.display='block'
        imgCode.onload=function(){
            let prev = base64Data;
            base64Data = getBase64Image(imgCode);
            let titleDom = document.querySelector('.Order_info h3');
            if(titleDom){
                titleDom.innerText="验证码加载完毕";
            }
            if(prev){
              let dom = document.querySelector('.imgcode input');
              let buyTip = document.querySelector('.buytip').style.display;
                 if(buyTip!='none'){
                     window.postUrl(base64Data,dom,(res)=>{
                         let buyTip = document.getElementsByClassName('buytip')[0].getAttribute('style');
                         document.querySelector('.gorushbuy').click();

                     })
                 }
            }
        }
    }

    checkBuyCode();

     window.onload=function(){
         let ms = targetDate.getTime()-new Date().getTime()-500;
         console.log("活动将在 "+ms+"ms 后开始");

         let titleDom = document.querySelector('.Order_info h3');
         if(titleDom){
             titleDom.innerText="活动将在 "+ms+"ms 后开始,请确认是否已经登录";
         }else{
             return;
         }
         console.log(targetDate)

         let totalNum = document.querySelector('.totalNum')
         if(totalNum&&totalNum.innerText==='0张'){
             document.querySelector('.Order_info h3').innerText='已售罄，期待下次抢购吧';
             return;
         }

         setTimeout(quickBuy,ms)

         if(week===5&&hour===10&&minute===59&sec===58){
             console.log("***** 活动时间即将开始 *****");
         }else{
             console.log("活动尚未开始,当前时间：周"+week+" "+hour+":"+minute);
             if(week===5){
                 setTimeout(function(){
                     location.reload();
                 },5000)
             }
         }
     }

})();